<template>
  <!-- 计算公式维护编辑 -->
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin
        :spinning="loading"
        class="form-item"
      >
        <!-- 表单 -->
        <a-card>
          <title-name title="工程基本情况"></title-name>
          <custom-form
            :isEmit="false"
            :formList="formList"
            :form="form"
            :editModel="editModel == 0 ? '' : ''"
          > </custom-form>
        </a-card>
        <a-card>
          <title-name title="不参加考核指标"></title-name>
          <div>请勾选不参加考核的指标，并填写无法参加考核的原因<span style="color: chocolate">（所在月份的“不参加考核指标申请”只适用于该月）</span>。</div>
          <s-table
            ref="table"
            :page-keys="['pageNum', 'pageSize']"
            tableLayout="fixed"
            size="default"
            rowKey="code"
            :row-selection="rowSelection"
            :columns="columns"
            :data="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
          >
            <template
              slot="remarks"
              slot-scope="text, record"
              class="form-item"
            >
              <BaseInput
                :class="record.check ? '' : 'remark'"
                :disabled="editModel == 0"
                placeholder="请输入"
                v-model.trim="record.remarks"
              ></BaseInput>
            </template>
          </s-table>
        </a-card>
        <!-- 页脚操作栏 -->
        <div
          class="btn_box page-btn-right-top"
          v-if="editModel != 0 && !isConsultation"
        >
          <a-button
            class="button_right"
            v-if="form.auditStatus == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
          >保存</a-button>
          <a-button
            v-else
            class="button_right"
            type="primary"
            :loading="loadingBtn.DRAFT"
            @click="handleSubmit('DRAFT')"
          >保存草稿</a-button>
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
          >提交</a-button>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div
          class="btn_box page-btn-right-top"
          v-else-if="!isConsultation"
        >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
    <!-- 选择审批人 -->
  </base-breadcrumb>
</template>

<script>
import { api } from '@/api/project/performanceAnalysis'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
const columns = [
  {
    title: '指标',
    dataIndex: 'name'
  },
  {
    title: '无法参加考核原因',
    dataIndex: 'remarks',
    scopedSlots: { customRender: 'remarks' }
  }
]
export default {
  name: 'projectAuthorizationLetter',
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany
  },

  data() {
    this.columns = columns
    return {
      loading: false, // 加载控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      form: { keyProgram: '', month: '', detailsList: [] }, // 表单
      id: '',
      selectedRowKeys: [],
      status: ['DRAFT', 'SUBMITTED', 'UPLOAD', 'PAST', 'ABOLISH', 'REJECTED'],
      update: null,
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.detailsList || []
          })
        })
      },
      rules: { month: [{ required: true, message: '请选择' }] }, // 校验规则
      init: false, // 初始化控件
      orgLevel: '',
      hasProject: false,
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('project_lvyue_formula')
  },
  mounted() {
    this.orgLevel = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.currentPost?.code
    // 不为添加时请求详情
    this.$route.meta.title = '不考核申请'
    if (this.editModel != 2) {
      this.getDetailData()
    } else {
      this.$nextTick(() => {
        this.getAuditProject()
        // 默认映射联系人为登陆人
        this.getMonth()
        this.getTable()
        this.init = true
      })
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: (record) => ({
          props: {
            defaultChecked: this.selectedRowKeys.includes(record.code),
            disabled: this.editModel == 0
          }
        })
      }
    },
    formList() {
      const key = this.hasProject ? 'projectId' : 'branchCompanyId'
      console.log(key,'key')
      return [
        {
          type: 'orgTree',
          keyName: key, // 'branchCompanyId',
          label: '所属单位',
          disabled: true,
          isShowProject: key !== 'branchCompanyId',
          span: 16
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: async (e) => {
        //     const res = await getProjectInfo({ projectId: e.code })
        //     this.form.keyProgram = res.data.keyProjectsName
        //     console.log(res, 'keyProjectsName')
        //   }
        // },

        {
          keyName: 'keyProgram',
          type: 'BaseInput',
          disabled: true,
          label: '是否重点项目'
        },

        {
          keyName: 'month',
          type: 'a-month-picker',
          placeholder: '请选择日期',
          label: '月份',
          disabled: this.editModel == 0,
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        }
      ]
    }
  },
  methods: {
    getAuditProject() {
      const data = {
        deptOrgIds: [this.$userInfo().currentPost.id]
      }
      if (this.orgLevel != 'PD') {
        data.branchComIds = [this.$userInfo().currentPost.orgId]
      }
      this.form.branchCompanyId = this.$userInfo().currentPost.orgId

      getAuditProject(data).then(async (res) => {
        if (res.data && res.data.length) {
          this.form.projectId = res.data[0].projectId
          const resp = await getProjectInfo({ projectId: this.form.projectId })
          this.form.keyProgram = resp.data.keyProjectsName
          this.hasProject = true
          console.log(this.form.projectId, ' this.form.projectId')
          this.$forceUpdate()
        }
      })
    },
    onSelectChange(selectedRowKeys) {
      console.log(selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      this.updateTable()
    },
    async getMonth() {
      if (this.month) {
        this.form.month = this.month
        return
      }
      const res = await api.getNoAssessmentMonth({ projectId: this.$userInfo().currentPost.deptId })
      console.log(res)
      this.form.month = res.data
    },
    async getTable() {
      this.$refs.table.localLoading = true
      const res = await api.getNoAssessmentDataList()
      this.$refs.table.localLoading = false
      this.form.detailsList = res.data
      this.$refs.table.refresh(true)
    },
    getDetailData() {
      this.loading = true
      api
        .getNoAssessment({ id: this.id })
        .then((res) => {
          this.loading = false
          if (res.data.projectId) {
            this.hasProject = true
          }
          this.form = { ...res.data }
          this.$refs.table.refresh()
          this.form.detailsList.forEach((e) => {
            if (e.check) {
              this.selectedRowKeys.push(e.code)
            }
          })
          // this.$refs.table.refresh()
          console.log(this.selectedRowKeys)

          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    updateTable() {
      this.form.detailsList.forEach((e) => {
        e.check = false
        this.selectedRowKeys.forEach((i) => {
          if (i == e.code) {
            e.check = true
          }
        })
      })
      // this.$refs.table.refresh(true)
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag1 = true
      let flag2 = true
      let flag3 = false
      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      this.form.detailsList.forEach((i) => {
        if (i.check) {
          flag3 = true
        }
        if (i.check && !i.remarks) {
          flag2 = false
        }
      })
      if (!flag3) {
        this.$message.warning('请至少勾选一项不参加考核的指标')
      }
      if (!flag2) {
        this.$message.warning('请填写勾选指标无法参加考核的原因')
      }
      if (flag1 && flag2 && flag3) {
        return true
      } else {
          this.$message.warning("请填写完所有必填项信息")
        return false
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      try {
        if (status == 'SUBMITTED' && !this.validateForm()) {
          return
        }
        const req = [api.updateNoAssessment, api.addNoAssessment][this.editModel - 1]
        let form = this.$clone(this.form)

        form.auditStatus = status
        this.setProcessConfig = null
        this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, (flag)=>{
              if(!flag) {
                  this.loading[auditStatus] = false
                  return
                }
             if (status == 'SUBMITTED') {
               return req(form)
                .then((res) => {
                  if (res.code == 200 || res.code == 0) {
                    this.$message.success('提交成功')
                    this.businessId = res.data.id
                    this.setProcessConfig = this.processConfig
                  } else {
                    this.loading = false
                  }
                })
                .catch(() => {
                  this.loading = false
              })
          return
        }
        this.loading = true
        req(form)
          .then((res) => {
            console.log(res)
            if (res.code == 200) {
              this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
              if (status == 'SUBMITTED') {
                this.businessId = res.data.id
                this.setProcessConfig = this.processConfig
              } else {
                this.$multiTab.close()
              }
            }
          })
          .catch(() => {
            this.loading = false
            this.$message.warning(err.data.message)
          })

              })
   
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;

    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }

  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
